package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.service.MinIOService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "minio接口")
@Slf4j
public class MinIOController {

    @Autowired
    private MinIOService minioService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            log.info("文件上传开始: " + file.getOriginalFilename());
            String FileUrl = minioService.uploadFile(file);
            log.info("文件路径: " + FileUrl);
            return Result.success(FileUrl);
        } catch (Exception e) {
            log.error("文件上传失败: " + e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("objectName") String objectName) {
        try {
            log.info("文件下载开始: " + objectName);
            InputStream inputStream = minioService.downloadFile(objectName);
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + objectName);
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete")
    public String deleteFile(@RequestParam("objectName") String objectName) {
        try {
            minioService.deleteFile(objectName);
            return "文件删除成功: " + objectName;
        } catch (Exception e) {
            return "文件删除失败: " + e.getMessage();
        }
    }

    /**
     * 获取文件的临时访问 URL
     */
    @GetMapping("/url")
    public String getFileUrl(@RequestParam("objectName") String objectName) {
        try {
            log.info("获取文件 URL 开始: " + objectName);
            return minioService.getFileUrl(objectName);
        } catch (Exception e) {
            return "获取文件 URL 失败: " + e.getMessage();
        }
    }
}
